<?php
namespace app\admin\model;
use app\common\model\StoreUser as StoreUserModel;
use think\Db;
/**
 * 商户用户模型
 */
class StoreUser extends StoreUserModel
{
	
	/**
	 * 公众号一键同步用户
	*/
	public function wechat()
	{
		$access_token = getAccessToken('',0);
		$url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid=';
		$result = json_decode(curl($url),true);
		if(!isset($result['data'])){
			$this->error = '获取用户列表失败';
			return false;
		}
		$wechatUser = [];
		//以此获取用户详情
		foreach($result['data']['openid'] as $openid){
			$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
			$result = json_decode(curl($url),true);
			//判断是否获取成功
			if(isset($result['unionid'])){ 
				array_push($wechatUser,$result);
			}
		}
		$newUser = [];//新用户
		$editUser = [];//更新用户
		$userList = $this->useGlobalScope(false)->select();//获取本地所有用户信息
		for($n=0;$n<sizeof($wechatUser);$n++){
			$new = 1 ;//是否为新用户
			for($m=0;$m<sizeof($userList);$m++){
				if($wechatUser[$n]['unionid']==$userList[$m]['union_id']){
					$new = 0;//不是新用户，下面更新用户信息
					$user = [];
					$user['store_user_id'] = $userList[$m]['store_user_id'];
					$user['wechat_open_id'] = $wechatUser[$n]['openid'];
					$user['nickName'] = $wechatUser[$n]['nickname'];
					$user['avatarUrl'] = $wechatUser[$n]['headimgurl'];
					$user['gender'] = $wechatUser[$n]['sex'];
					$user['country'] = $wechatUser[$n]['country'];
					$user['province'] = $wechatUser[$n]['province'];
					$user['city'] = $wechatUser[$n]['city'];
					array_push($editUser,$user);
					break;
				}
			}
			if($new == 1){
				//筛选出来的新用户
				array_push($newUser,$wechatUser[$n]);
			}
		}
		 // 开启事务
        Db::startTrans();
        try {
			//批量更新老用户资料
			if(sizeof($editUser)>0){
				$this->isUpdate(true)->saveAll($editUser);
			}
			//批量新增微信端用户信息
			if(sizeof($newUser)>0){
				$user = [];
				for($n=0;$n<sizeof($newUser);$n++){
					$user[$n]['union_id'] = $newUser[$n]['unionid'];
					$user[$n]['wechat_open_id'] = $newUser[$n]['openid'];
					$user[$n]['nickName'] = $newUser[$n]['nickname'];
					$user[$n]['avatarUrl'] = $newUser[$n]['headimgurl'];
					$user[$n]['gender'] = $newUser[$n]['sex'];
					$user[$n]['country'] = $newUser[$n]['country'];
					$user[$n]['province'] = $newUser[$n]['province'];
					$user[$n]['city'] = $newUser[$n]['city'];
				}
				$this->isUpdate(false)->saveAll($user);//新增用户数据
			}
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}
	
	/**
     * 重置商户密码
     */
    public function resetPwd($data)
    {
		$data['password'] = hema_hash('123456');
        if ($this->allowField(true)->save($data) === false) {
            return false;
        }
        return true;
    }
    
}
